﻿using System.Collections.Generic;
using System.Linq;
using Inscriptionem.ORM.Extensions;

namespace Inscriptionem.Models.Blog.Views
{
    public class SearchViewModel : BlogViewModel
    {
        public new string ID { get; set; }

        public IEnumerable<Article> Search(int SkipCount, int TakeCount)
        {
            List<Article> result = new List<Article>();

            // Pages
            var pages = Pages.Where(p => p.IsPublished).AsQueryable().FullTextSearch(ID).Distinct();

            int pagesCount = pages.Count();
            if (pagesCount < SkipCount)
            {
                result.AddRange(pages.OrderByDescending(p => p.ID).Skip(SkipCount).Take(TakeCount).Select(p => p.ToArticle()));
            }


            SkipCount -= (pagesCount/TakeCount) * TakeCount;
            if (SkipCount < 0)
            {
                SkipCount = 0;
            }

            // Posts
            var posts = SectionDataProvider.Categories.SelectMany(c => c.PostCategories).Select(pc => pc.Post).Where(p => p.IsPublished).AsQueryable().FullTextSearch(ID).Distinct();

            int postsCount = posts.Count();

            if (result.Count < TakeCount)
            {
                result.AddRange(posts.OrderByDescending(p => p.ID).Skip(SkipCount).Take(TakeCount - result.Count).Select(p => p.ToArticle()));
            }

            // Calculate pagination
            Pagination.CurrentPage = Navigation + 1;
            Pagination.TotalPages = (pagesCount + postsCount) / Configuration.Configuration.Instance.Blog.PageSize + 1;

            return result;
        }
    }
}